//
//  CommoditySelectionView.swift
//  OnceNectar
//
//  Created by on 2018/2/7.
//  Copyright © 2018年 com.inwhoop. All rights reserved.
//

import UIKit

class CommoditySelectionView: UIView, AddCornerUIRectCorner {
    
    private let mainView = BaseCircleView()
    private let bottomOffset: CGFloat = 5
    private let bottombuttonMargin: CGFloat = 20
    private let bottomViewHeight: CGFloat = 48
    private let mainViewSideMargin: CGFloat = 10
    private let topGrayViewHeight: CGFloat = 26
    private let itemImageViewLeftMargin: CGFloat = 25
    private let itemImageViewTopMargin: CGFloat = 10
    private let itemImageViewWidth: CGFloat = 135
    private let itemImageViewHeight: CGFloat = 120
    private let priceLeftMargin: CGFloat = 31
    private let priceTopMargin: CGFloat = 95
    private let originalPriceLabelTopMargin: CGFloat = 100
    private let originalPriceLabelLeftMargin: CGFloat = 5
    private let specificationPlaceholderLabelTopMargin: CGFloat = 17
    private let lineViewTopBottomMargin: CGFloat = 10
    private let lineViewHeight: CGFloat = 1
    private var leftTap:((NSInteger) -> Void)?
    private var rightTap:((_ model: SpecificationsModel, _ number: Int, _ index: Int) -> Void)?
    var xbeforButton: BaseCircularButton? = nil
    let priceLabel = UILabel()
    let remainLabel = UILabel()
    let originalPriceLabel = UILabel()
    let specificationPlaceholderLabel = UILabel()

    typealias selectBlock = (_ model: SpecificationsModel?, _ number: Int) -> Void
    var selectblock: selectBlock?
    
    var tempModel: SpecificationsModel?
    var number: Int = 1
    var goodModel :GoodsModel?
    /// 自定义初始化方法
    ///
    /// - Parameter items: 暂时用String代替
    init(items: GoodsModel) {
        super.init(frame: .zero)
        setUI(model: items)
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setUI(model: GoodsModel) {
        let window = UIApplication.shared.keyWindow
        guard let trueWindow = window else {
            return
        }
        goodModel = model
        
        self.tempModel = model.specifications?[0]
        self.backgroundColor = ONColor.maskBGColor
        self.frame = trueWindow.frame
        trueWindow.addSubview(self)
        self.alpha = 0.2
        let specifications = model.specifications?[0]
        
        if self.subviews.contains(mainView){
            mainView.removeFromSuperview()
        }
        
        mainView.frame = CGRect(x: mainViewSideMargin, y: ScreenHeight, width: ScreenWidth - mainViewSideMargin * 2, height: 200)
        mainView.backgroundColor = UIColor.white
        self.addSubview(mainView)
        
        let topGrayView = UIView()
        topGrayView.backgroundColor = ONColor.subOtherViewBGColor
        mainView.addSubview(topGrayView)
        topGrayView.frame = CGRect(x: 0, y: 0, width: mainView.width, height: topGrayViewHeight)
        addCornerWithView(aView: topGrayView, aCorners: [.topLeft, .topRight], aSize: CGSize(width: CORNERRADIUS, height: CORNERRADIUS))
        
        let cancelButton = UIButton(type: .custom)
        cancelButton.setImage(UIImage(named: "btn_delete"), for: .normal)
        cancelButton.sizeToFit()
        cancelButton.addTarget(self, action: #selector(cancelTap), for: .touchUpInside)
        topGrayView.addSubview(cancelButton)
        cancelButton.snp.makeConstraints { (make) in
            make.right.equalTo(topGrayView.snp.right).offset(-15)
            make.centerY.equalTo(topGrayView.snp.centerY)
        }
        
        
        let itemImageView = UIImageView()
        let path:String = "\(BaseURL)\(model.coverPath!)"
        
        
        let url = NSURL.init(string: path.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)
        itemImageView.sd_setImage(with:url! as URL,completed: nil)

        mainView.addSubview(itemImageView)
        itemImageView.frame = CGRect(x: itemImageViewLeftMargin, y: topGrayView.bottom + itemImageViewTopMargin, width: itemImageViewWidth, height: itemImageViewHeight)
        itemImageView.clipsToBounds = true
        itemImageView.contentMode = .scaleAspectFill
        
        priceLabel.textColor = ONColor.pirceLabelColor
        priceLabel.font = UIFont.systemFont(ofSize: 14)
        priceLabel.text = "￥ " + (specifications?.price!)!
        priceLabel.sizeToFit()
        mainView.addSubview(priceLabel)
        priceLabel.frame.origin = CGPoint(x: itemImageView.right + priceLeftMargin, y: priceTopMargin)
        
        
        originalPriceLabel.font = UIFont.systemFont(ofSize: 10)
        originalPriceLabel.textColor = ONColor.subTextColor
        let str1:String = "￥ " + (specifications?.originalPrice!)!
        originalPriceLabel.attributedText = NSMutableAttributedString.strikethrough(str: str1)
        originalPriceLabel.sizeToFit()
        mainView.addSubview(originalPriceLabel)
        originalPriceLabel.frame.origin = CGPoint(x: priceLabel.right + originalPriceLabelLeftMargin, y: originalPriceLabelTopMargin)
        
        specificationPlaceholderLabel.attributedText = NSMutableAttributedString.differentColorAndSizeString(first: (firstString: "已选：", firstColor: ONColor.subTextColor, firstSize: 12), second: (secondString: specifications?.color! as! NSString, secondColor: ONColor.normalTextColor, secondSize: 13))
        specificationPlaceholderLabel.sizeToFit()
        mainView.addSubview(specificationPlaceholderLabel)
        specificationPlaceholderLabel.frame.origin = CGPoint(x: itemImageView.right + priceLeftMargin, y: priceLabel.bottom + specificationPlaceholderLabelTopMargin)
        
        let firstLineView = UIView()
        firstLineView.backgroundColor = ONColor.cutLineColor
        mainView.addSubview(firstLineView)
        firstLineView.frame = CGRect(x: mainViewSideMargin, y: itemImageView.bottom + lineViewTopBottomMargin, width: mainView.width - mainViewSideMargin * 2, height: lineViewHeight)
        
        let specificationLabel = UILabel()
        specificationLabel.text = "颜色"
        specificationLabel.font = UIFont.systemFont(ofSize: 14)
        specificationLabel.textColor = ONColor.subTextColor
        specificationLabel.sizeToFit()
        mainView.addSubview(specificationLabel)
        specificationLabel.frame.origin = CGPoint(x: itemImageViewLeftMargin, y: firstLineView.bottom + lineViewTopBottomMargin)
        
        var titils:[String] = [String]()
        for subject in model.specifications! {
            titils.append(subject.color!)
        }
        
        
        /// 暂时搞的莫得时间了 normalTextColor
//        var beforButton: BaseCircularButton? = nil
        var leftOffset = itemImageViewLeftMargin + 10
        for (index, title) in titils.enumerated() {
            let button = BaseCircularButton(title: title, fontSize: 13, titleSideOffset: 3, titleColor: .gray,titleSelectColor:.black, borderColor: .gray)
            button.setTitle(title, for: .normal)
            button.addTarget(self, action: #selector(colorSelect(sender:)), for: .touchUpInside)
            
            let buttnMargin: CGFloat = 25
            button.tag = index
            button.frame = CGRect(x: leftOffset , y: specificationLabel.bottom + 20, width: button.buttonSize.width, height: button.buttonSize.height)
            mainView.addSubview(button)
            button.setTitleColor(UIColor.gray, for: .normal)
            button.setTitleColor(UIColor.black, for: .selected)

            leftOffset += (button.buttonSize.width +  buttnMargin)
            if index == 0 {
                xbeforButton = button
                button.isSelected = true
            }
        }
        
        let secondLineView = UIView()
        secondLineView.backgroundColor = ONColor.cutLineColor
        mainView.addSubview(secondLineView)
        secondLineView.frame = CGRect(x: mainViewSideMargin, y: xbeforButton!.bottom + lineViewTopBottomMargin * 2, width: mainView.width - mainViewSideMargin * 2, height: lineViewHeight)
        
        let numberPlaceholderLabel = UILabel()
        numberPlaceholderLabel.text = "数量"
        numberPlaceholderLabel.textColor = ONColor.subTextColor
        numberPlaceholderLabel.font = UIFont.systemFont(ofSize: 14)
        numberPlaceholderLabel.sizeToFit()
        mainView.addSubview(numberPlaceholderLabel)
        numberPlaceholderLabel.frame.origin = CGPoint(x: itemImageViewLeftMargin, y: secondLineView.bottom + lineViewTopBottomMargin)
        
        let numberLabel = UILabel()
        numberLabel.textColor = UIColor(hex: 0x949494)
        numberLabel.text = "1"
        numberLabel.tag = 998
        numberLabel.textAlignment = .center
        numberLabel.font = UIFont.systemFont(ofSize: 15)
        numberLabel.sizeToFit()
        let textWidht = numberLabel.text?.sizeOfString(usingFont: UIFont.systemFont(ofSize: 15))
        numberLabel.frame = CGRect(x: numberPlaceholderLabel.right  , y: secondLineView.bottom + 37, width: textWidht! + 25.0, height: 20.0)
        numberLabel.layer.cornerRadius = numberLabel.height / 2
        numberLabel.layer.borderColor = UIColor(hex: 0x949494).cgColor
        numberLabel.layer.borderWidth = 2
        mainView.addSubview(numberLabel)
        
        let reducebutton = UIButton(type: .custom)
        reducebutton.setTitle("-", for: .normal)
        reducebutton.titleLabel?.font = UIFont.systemFont(ofSize: 18)
        reducebutton.setTitleColor(UIColor(hex: 0x949494), for: .normal)
        reducebutton.frame = CGRect(x: numberLabel.left - 50, y: secondLineView.bottom + 15, width: 50, height: 50)
        reducebutton.centerY = numberLabel.centerY
        reducebutton.addTarget(self, action: #selector(reduceClick(sender:)), for: .touchUpInside)
        mainView.addSubview(reducebutton)
        
        let addButton = UIButton(type: .custom)
        addButton.setTitle("+", for: .normal)
        addButton.setTitleColor(UIColor(hex: 0x949494), for: .normal)
        addButton.titleLabel?.font = UIFont.systemFont(ofSize: 18)
        addButton.frame = CGRect(x: numberLabel.right, y: secondLineView.bottom + 20, width: 50, height: 50)
        addButton.centerY = numberLabel.centerY
        addButton.addTarget(self, action: #selector(addClick(sender:)), for: .touchUpInside)
        mainView.addSubview(addButton)
        
        remainLabel.textColor = UIColor(hex: 0x949494)
        let num:Int = Int(model.specifications![0].inventory!)!
        if num < 10 {
            remainLabel.textColor = UIColor.red
        }
        if num == 0 {
            remainLabel.text = "暂无库存"
        }else {
            remainLabel.text = "剩余\(num)件"
        }
        remainLabel.tag = 999
        remainLabel.textAlignment = .left
        remainLabel.font = UIFont.systemFont(ofSize: 14)
        remainLabel.sizeToFit()
        remainLabel.frame = CGRect(x: addButton.right + 10  , y: addButton.y, width: 100, height: 30.0)
        remainLabel.centerY = addButton.centerY
        mainView.addSubview(remainLabel)
        
        
        let topHeight = topGrayView.height + itemImageViewTopMargin + itemImageViewHeight + lineViewTopBottomMargin + lineViewHeight + lineViewTopBottomMargin + specificationLabel.height + 20 + xbeforButton!.height + lineViewTopBottomMargin * 2 + secondLineView.height + lineViewTopBottomMargin + numberLabel.height + 57
        bottomView(topHeight: topHeight)
        mainView.height = topHeight + bottomViewHeight
    }
    
    func bottomView(topHeight: CGFloat) {
        let bottomView = UIView(frame: CGRect(x: 0, y: topHeight, width: mainView.width, height: bottomViewHeight))
        bottomView.backgroundColor = UIColor.white
        mainView.addSubview(bottomView)
        addCornerWithView(aView: bottomView, aCorners: [.bottomLeft, .bottomRight], aSize: CGSize(width: CORNERRADIUS, height: CORNERRADIUS))
        var beforButton: UIButton?
        let lImageNames = ["customer_service_icon", "btn_shopping_detail"]
        for (index, image) in lImageNames.enumerated() {
            let leftButton = UIButton(type: .custom)
            leftButton.setImage(UIImage(named: image), for: .normal)
            leftButton.tag = index
            leftButton.sizeToFit()
            leftButton.addTarget(self, action: #selector(leftTaps(_ :)), for: .touchUpInside)
            bottomView.addSubview(leftButton)
            leftButton.snp.makeConstraints({ (make) in
                make.left.equalTo(beforButton == nil ? bottomView.snp.left : beforButton!.snp.right).offset(bottombuttonMargin)
                make.centerY.equalTo(bottomView.snp.centerY)
            })
            beforButton = leftButton
        }
        
        let titles = ["立即购买", "加入购物车"]
        let bgImageNames = ["buyNow_blue_bg", "btn_shoppingCart_affirm"]
        let buttonWidht: CGFloat = (mainView.width - beforButton!.width * 2 - bottombuttonMargin * 3) / 2
        for (index, title) in titles.enumerated() {
            let rightButton = UIButton(type: .custom)
            rightButton.setTitle(title, for: .normal)
            rightButton.setBackgroundImage(UIImage(named: bgImageNames[index]), for: .normal)
            rightButton.tag = index
            rightButton.addTarget(self, action: #selector(buyTap(_ :)), for: .touchUpInside)
            bottomView.addSubview(rightButton)
            rightButton.snp.makeConstraints({ (make) in
                make.left.equalTo(beforButton!.snp.right).offset(index == 0 ? bottombuttonMargin : 0)
                make.top.bottom.equalTo(bottomView)
                make.width.equalTo(buttonWidht)
            })
            beforButton = rightButton
        }
    }
    @objc func colorSelect(sender:UIButton) -> Void {
        print("-------")

        xbeforButton?.isSelected = false
        let xlineLayer = CAShapeLayer()
        xlineLayer.fillColor = UIColor.clear.cgColor
        xlineLayer.lineWidth = 2

        xlineLayer.strokeColor = UIColor.gray.cgColor
        xbeforButton?.layer.addSublayer(xlineLayer)

        
        sender.isSelected = true
        let lineLayer = CAShapeLayer()
        lineLayer.fillColor = UIColor.clear.cgColor
        lineLayer.lineWidth = 2

        lineLayer.strokeColor = UIColor.black.cgColor
        sender.layer.addSublayer(lineLayer)
        xbeforButton = (sender as! BaseCircularButton)
        
        
        let specifications = goodModel?.specifications![sender.tag]

        priceLabel.text = "￥ " + (specifications?.price!)!
        let str1:String = "￥ " + (specifications?.originalPrice!)!
        originalPriceLabel.attributedText = NSMutableAttributedString.strikethrough(str: str1)
        originalPriceLabel.sizeToFit()
        specificationPlaceholderLabel.attributedText = NSMutableAttributedString.differentColorAndSizeString(first: (firstString: "已选：", firstColor: ONColor.subTextColor, firstSize: 12), second: (secondString: specifications?.color! as! NSString, secondColor: ONColor.normalTextColor, secondSize: 13))
        let num:String = (specifications?.inventory)!
        if Int(num)! < 10 {
            remainLabel.textColor = UIColor.red
        }
        if Int(num)! == 0 {
            remainLabel.text = "暂无库存"
        }else {
            remainLabel.text = "剩余\(num)件"
        }
        priceLabel.sizeToFit()
        originalPriceLabel.frame.origin = CGPoint(x: priceLabel.right + originalPriceLabelLeftMargin, y: originalPriceLabelTopMargin)

        originalPriceLabel.sizeToFit()
        specificationPlaceholderLabel.sizeToFit()
        self.tempModel = specifications

    }
    @objc func reduceClick(sender:UIButton) -> Void{
        print("-------")
        let label:UILabel = mainView.viewWithTag(998) as! UILabel
        let num = Int(label.text!)
        if num! != 1{
            label.text = "\(num! - 1)"
            self.number = num! - 1
        }

    }
    @objc func addClick(sender:UIButton) -> Void{
        print("+++++++")
        let label:UILabel = mainView.viewWithTag(998) as! UILabel
        let num = Int(label.text!)
        self.number = num! + 1
        label.text = "\(num! + 1)"
    }
    @objc func leftTaps(_ btn: UIButton) {
        leftTap?(btn.tag)
        hide()
    }
    
    @objc func buyTap(_ btn: UIButton) {
        rightTap?(self.tempModel!, self.number, btn.tag)
        hide()
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        if (touches.first?.view!.isEqual(self))! {
            hide()
        }
    }
    
    func hide() {
        UIView.animate(withDuration: TimeInterval(anTIME), animations: {
            self.mainView.origin.y = ScreenHeight - Ipx(false).bottomMargin
        }) { (make) in
            self.removeFromSuperview()
        }
    }
    
    func show(leftButtonTaps: @escaping (NSInteger) -> Void, rightButtonTaps: @escaping (_ model: SpecificationsModel, _ number: Int, _ index: Int) -> Void) {
        leftTap = leftButtonTaps
        rightTap = rightButtonTaps
        UIView.animate(withDuration: TimeInterval(anTIME)) {
            self.alpha = 1
            self.mainView.frame.origin.y = ScreenHeight - self.mainView.height - Ipx(false).bottomMargin - self.bottomOffset
        }
    }
    
    @objc func doneButtonTap() {
        hide()
    }
    
    @objc func cancelTap() {
        hide()
    }
}
